package com.vdm.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.vdm.model.UserInfo;
import com.vdm.util.Constants;

public class UserLoginInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		UserInfo user = (UserInfo) request.getSession().getAttribute(Constants.CURRENT_USER);
		String url = request.getRequestURI() != null ? request.getRequestURI().toString() : null;
		System.out.println("url-->" + url);
		// System.out.println("user-->" + user.toString());
		if (user == null) {
			System.out.println("user is null");
			response.sendRedirect(request.getContextPath() + "/user/toLogin");
			return false;
		} else {
			if("/".equals(url) || url==null){
				response.sendRedirect(request.getContextPath() + "/user/toUserList");
				return false;
			}
			return true;
		}
	}

}
